function examT(value){
		if(value=='现场考试'){
		$("#txsz").hide();
	    $("#sjjg").hide();
	    $("#zf").show();
		}else{
			$("#txsz").show();
		    $("#sjjg").show();
		    $("#zf").hide();
		}
	}

$(function(){
	var dataJson=getFormDatatoJson("paper");
	var examType= $("#examType").val();
	if(examType=='现场考试'){
		$("#txsz").hide();
	    $("#sjjg").hide();
	    $("#zf").show();
		}else{
			$("#txsz").show();
		    $("#sjjg").show();
		    $("#zf").hide();
		}
	  $('#papers-name').blur(function(){
		           var papersname1=$(this).val();
		          $.ajax({
		              type:"post",
		              data:"t_papersname="+papersname1,
		              url:"/paperManager/paperNameCheck",
		             success:function(data){
		                 if(data.length>0&&data[0].name!=dataJson.name){
		                     $.Zebra_Dialog('<div class="prompt"><div class="error-icon"></div><div class="success-title">该试卷名称存在,请重新填写</div></div>', {
							   'title':'提示',
							   'buttons' : [ {
									caption : '确定',
									callback : function() {
										$('#papers-name').val("");
									}
								} ]
							});
		                 }
		              }
		          })
		      })
	//自动
    $('#autoPaper').on('click', function(e) {
    	if($("#radioCount").val()===null||$("#radioCount").val()===""){
    		document.getElementById("radioCount").value=0;
    	}
    	if($("#checkCount").val()===null||$("#checkCount").val()===""){
    		document.getElementById("checkCount").value=0;
    	}
    	if($("#judgeCount").val()===null||$("#judgeCount").val()===""){
    		document.getElementById("judgeCount").value=0;
    	}
    	if($("#fillCount").val()===null||$("#fillCount").val()===""){
    		document.getElementById("fillCount").value=0;
    	}
    	var radioCount=$("#radioCount").val();
    	var checkCount=$("#checkCount").val();
    	var judgeCount=$("#judgeCount").val();
    	var fillCount=$("#fillCount").val();
    	
    	var jsondata={};
    	if (radioCount) {
    		jsondata.radioCount=radioCount;
		}
    	if (checkCount) {
    		jsondata.checkCount=checkCount;
    	}
    	if (judgeCount) {
    		jsondata.judgeCount=judgeCount;
    	}
    	if (fillCount) {
    		jsondata.fillCount=fillCount;
    	}
    	var dataJson=getFormDatatoJson("paper");
    	if (dataJson.examType!='考试试卷') {
    		if($("#askCount").val()===null||$("#askCount").val()===""){
    			document.getElementById("askCount").value=0;
    		}
    		var askCount=$("#askCount").val();
    		if (askCount) {
	    		jsondata.askCount=askCount;
	    	}
		} 
    	console.log(jsondata);
    	$.ajax({
             type: "post",
             url: "/questions/selQuestions",
             data: jsondata,
             success: function(data){
            	$("#questions").empty();
            	var strhtml='<div id="chosequestions"><div class="paper-d"><div class="paper-d-title">一、单选题</div></div></div>'
            	            +'<div id="checkquestions"><div class="paper-d"><div class="paper-d-title">二、多选题</div></div></div>'
            	            +'<div id="judequestions"><div class="paper-d"><div class="paper-d-title">三、判断题</div></div></div>'
            	            +'<div id="fillquestions"><div class="paper-d"><div class="paper-d-title">三、填空题</div></div></div>'
            	            +'<div id="askquestions"><div class="paper-d"><div class="paper-d-title">四、问答题</div></div></div>';
            	$("#questions").append(strhtml);
            	if(data.radioList!=null){
            		$.each(data.radioList,function(index,d){
    				    $("#chosequestions").append(showQuestion(index+1,d.content,d.id));
                    });
            	}
            	console.log(data);
            	if(data.checkList!=null){
            		$.each(data.checkList,function(index,d){
                		$("#checkquestions").append(showQuestion(index+1,d.content,d.id));
                	});
            	}
            	
            	if(data.judeList!=null){
            		$.each(data.judeList,function(index,d){
                		$("#judequestions").append(showQuestion(index+1,d.content,d.id));
                	});
            	}
            	
            	if(data.fillList!=null){
            		$.each(data.fillList,function(index,d){
                		$("#fillquestions").append(showQuestion(index+1,d.content,d.id));
                	});
            	}
            	
            	if(data.askList!=null){
            		$.each(data.askList,function(index,d){
                		$("#askquestions").append(showQuestion(index+1,d.content,d.id));
                	});
            	}
            }
         });
    	
    });
    
    //保存试卷
    $('#savePaper').on('click', function(e) {
    	var dataJson=getFormDatatoJson("paper");
    	var flag=validate(dataJson);
    	if(flag){
    	$.ajax({
            url: '/paperManager/savePaper',
            type: 'post',
            async:false,
            cache:false,
            dataType:'json',
            data: dataJson,
		    success: function (data) {
		    	console.log(data);
		    	if(data=="1"){
		    		 $.Zebra_Dialog('<div class="prompt"><div class="success-icon"></div><div class="success-title">保存成功!</div></div>', {
			                'title': '提示',
			                'buttons' : [ {
								caption : '确定',
								callback : function() {
									window.location.href="/paperManager/papers";
								}
							} ]
			            });
		    	}else{
		    		zebra_Dialog_warning("保存失败!");
		    	}
		    }
	  });
    	}
    });
  //修改试卷
    $('#updatePaper').on('click', function(e) {
    	var dataJson=getFormDatatoJson("paper");
    	var flag=validate(dataJson);
    	if(flag){
    		$.ajax({
                url: '/paperManager/updatePaper',
                type: 'post',
                async:false,
                cache:false,
                dataType:'json',
                data: dataJson,
    		    success: function (data) {
    		    	if(data=="1"){
    		    		 $.Zebra_Dialog('<div class="prompt"><div class="success-icon"></div><div class="success-title">修改成功!</div></div>', {
    			                'title': '提示',
    			                'buttons' : [ {
    								caption : '确定',
    								callback : function() {
    									window.location.href="/paperManager/papers";
    								}
    							} ]
    			            });
    		    		
    		    	}else{
    		    		zebra_Dialog_warning("修改失败!");
    		    	}
    		    }
    	  });
    	}
    	
    });
    //手动组卷
    $("#manual-btn").click(function(){
    	$("#manual-show").show();
    	$("#addPaper").hide();
    	var dataJson=getFormDatatoJson("paper");
    	//已经选择的试题的id
    	var qids=dataJson.qids;
    	var qidstr='';
    	if(qids!=undefined){
    		$.each(qids,function(i,e){
        		var s=e.split("-");
        		qidstr+=s[0]+",";
        	});
    	}
    	
    	//默认显示单选题界面
    	$(".questionsa-add li a").removeClass("active");
    	$(".questionsb-add").hide();
    	$(".questionsa-add li a").eq(0).addClass("active");
        $(".questionsb-add").eq(0).show();
        //默认显示单选题界面
        var code='单选题';
        commajax(code,qidstr);
    });
    
    var dataJson=getFormDatatoJson("paper");
	hiddenScore(dataJson.examType);
	
	$(".spare-add-select").change(function(){
  	  var option=$(this).val();
  	  hiddenScore(option);
  	});
});
function switchCode(code){
	var dataJson=getFormDatatoJson("paper");
	var qids=dataJson.qids;
	var qidstr='';
	if(qids!=undefined){
		$.each(qids,function(i,e){
    		var s=e.split("-");
    		qidstr+=s[0]+",";
    	});
	}
	commajax(code,qidstr);
	
	
}
function commajax(code,qidstr){
	$.ajax({
        url: '/paperManager/selquestions',//查询
        type: 'post',
        dataType:'json',
        data: {'code':code},
	    success: function (data) {
	    	if(code=='单选题'){
	    		commstr("choseq",data,qidstr);
	    	}else if(code=='判断题'){
	    		commstr("judgeq",data,qidstr);
	    	}else if(code=='多选题'){
	    		commstr("moreq",data,qidstr);
	    	}else if(code=='问答题'){
	    		commstr("askq",data,qidstr);
	    	}else if(code=='填空题'){
	    		commstr("filleq",data,qidstr);
	    	}
	    }
  });
}
function commstr(id,data,qidstr){
	$("#"+id).empty();
	$.each(data,function(i,e){
		var str='';
		if(qidstr.indexOf(e.id)!=-1){
			str+='<div class="manual-a clearfix active" id="'+e.id+'"><div class="paper-el">'+(i+1)+'.</div>';
		}else{
			str+='<div class="manual-a clearfix" id="'+e.id+'"><div class="paper-el">'+(i+1)+'.</div>';
		}
		str+='<div class="manual-ar">'+e.content+'</div><div class="documentation-check"></div></div>';
		$("#"+id).append(str);
		$("#"+id).find(".manual-a").unbind();
		$("#"+id).find(".manual-a").click(function() {
			$(this).toggleClass("active");
		});
	});
}
function hideManual(){
	$("#manual-show").hide();
	$("#addPaper").show();
	$("#questions").empty();
	var strhtml='<div id="chosequestions"><div class="paper-d"><div class="paper-d-title">一、单选题</div></div></div>'
	            +'<div id="checkquestions"><div class="paper-d"><div class="paper-d-title">二、多选题</div></div></div>'
	            +'<div id="judequestions"><div class="paper-d"><div class="paper-d-title">三、判断题</div></div></div>'
	            +'<div id="askquestions"><div class="paper-d"><div class="paper-d-title">四、问答题</div></div></div>';
	$("#questions").append(strhtml);
	//-----------单选题-----------------------
	commEach("choseq","chosequestions");
	//-----------单选题-----------------------
	//-----------多选题-----------------------
	commEach("moreq","checkquestions");
	//-----------多选题-----------------------
	//-----------问答题-----------------------
	commEach("askq","askquestions");
	//-----------问答题-----------------------
	//-----------判断题-----------------------
	commEach("judgeq","judequestions");
	//-----------判断题-----------------------
	commEach("filleq","fillquestions");
	//-----------填空题-----------------------
	
}
function commEach(judgeq,judequestions){
	var judgeqDivs=$("#"+judgeq).find(".active");//获得所有被选中的div
	var judgeqArray=new Array();
	$.each(judgeqDivs,function(i,e){
		var q={};
		q.id=$(this).attr("id");
		q.content=$(this).find(".manual-ar").text();
		judgeqArray.push(q);
	});
	$.each(judgeqArray,function(index,d){
	    $("#"+judequestions).append(showQuestion(index+1,d.content,d.id));
    });
}
function getFormDatatoJson(id) {
    var dataJson = {};
    $("#"+id).serializeArray().map(function (x) {
        if (dataJson[x.name ] !== undefined) {
            if (!dataJson[x.name].push) {
                dataJson[x.name] = [dataJson[x.name]];
            }
            dataJson[x.name].push(x.value || '');
        } else {
            dataJson[x.name] = x.value || '';
        }
    });
    return dataJson;
}
function showQuestion(index,content,qid){
	var question='<div class="paper-e clearfix" id="'+qid+'">'
		+'<div class="paper-el">'+index+'.</div>'
		+'<div class="paper-em">'+content+'</div>'
		+'<div class="paper-er"><a href="#" onclick=upMove(\"'+qid+'\")>上 移</a><a href="#" onclick=downMove(\"'+qid+'\")>下 移</a><a href="#" onclick=delquestion(\"'+qid+'\")>删 除</a></div>'
		+'<input  name="qids" type="hidden" value="'+qid+'-'+index+'"/></div>';
	return question;
	
}
function delquestion(qid){
	var allBrothers=$("#"+qid).nextAll();//当前元素之后的所有兄弟节点
	allBrothers.each(function(index,element){
		var sequence=$(this).find(".paper-el").text().replace(".","");//获得当前序号
		$(this).find(".paper-el").text((sequence-1)+".");//重新赋值序号
		var qid=$(this).find("input").val();
		var  arr=qid.split('-');
		$(this).find("input").val(arr[0]+"-"+parseInt(arr[1]-1));
		
	});
	$("#"+qid).remove();
	
}
function upMove(qid){
	var brothers=$("#"+qid).prevAll();//当前元素的上一个兄弟节点
	var brother=$("#"+qid).prev();//当前元素的上一个兄弟节点
	if(brothers.length>1){
		var myself=$("#"+qid);
		var sequence=brother.find(".paper-el").text().replace(".","");//获得当前序号
		brother.find(".paper-el").text((parseInt(sequence)+1)+".");
		var se=myself.find(".paper-el").text().replace(".","");//获得当前序号
		myself.find(".paper-el").text((parseInt(se)-1)+".");
		brother.insertAfter($("#"+qid));
		myself.find("input").val(qid+'-'+(parseInt(se)-1));
		var qd=brother.attr('id')+'-'+(parseInt(sequence)+1);
		brother.find("input").val(qd);
	}else{
		zebra_Dialog_warning("已经是最顶端!");
	};
}
function downMove(qid){
	var brother=$("#"+qid).next();//当前元素的下一个兄弟节点
	if(brother.length>0){
		var myself=$("#"+qid);
		var sequence=brother.find(".paper-el").text().replace(".","");//获得当前序号
		brother.find(".paper-el").text((parseInt(sequence)-1)+".");
		var se=myself.find(".paper-el").text().replace(".","");//获得当前序号
		myself.find(".paper-el").text((parseInt(se)+1)+".");
		brother.insertBefore($("#"+qid));
		myself.find("input").val(qid+'-'+(parseInt(se)+1));
		var qd=brother.attr('id')+'-'+(parseInt(sequence)-1);
		brother.find("input").val(qd);
	}else{
		zebra_Dialog_warning("已经是最低端!");
	};
	
	
}

function validate(dataJson){
	//校验
	if(dataJson.name==''){
		zebra_Dialog_warning("试卷名称不能为空!");
		return ;
	}
	if(dataJson.totalTime=="0.0"||dataJson.totalTime=="0"){
		zebra_Dialog_warning("试卷时长不能为0!");
		return ;
	}
	var  regEn = /[~!@#$%^&*]/im,
    regCn = /[！#￥]/im;
	  if (regEn.test(dataJson.name) || regCn.test(dataJson.name)){
			top.$.Zebra_Dialog('<div class="prompt"><div class="warning-icon"></div><div class="success-title">试卷名称不能含有特殊字符</div></div>', {
				'title':'提示',
	 	         'buttons':['确定']
		     });
			return
	  }

	if(dataJson.name.length>20){
		zebra_Dialog_warning("试卷名称不能超出20个字符!");
		return ;
	}
		if(!(/^\d+(\.\d+)?$/.test(dataJson.totalTime))&&!(/(^[0-9]\d*$)/.test(dataJson.totalTime))){
			zebra_Dialog_warning("考试时长请输入非负数!");
			return ;
		}
		
		if(!(/(^[0-9]\d*$)/.test(dataJson.radioCount))&&dataJson.examType!='现场考试'){
			zebra_Dialog_warning("单选题请输入0或者正整数!");
			return ;
		}
		if(!(/(^[0-9]\d*$)/.test(dataJson.checkCount))&&dataJson.examType!='现场考试'){
			zebra_Dialog_warning("多选题请输入0或者正整数!");
			return ;
		}
		if(!(/(^[0-9]\d*$)/.test(dataJson.judgeCount))&&dataJson.examType!='现场考试'){
			zebra_Dialog_warning("判断题请输入0或者正整数!");
			return ;
		}
		if(!(/(^[0-9]\d*$)/.test(dataJson.askCount))&&dataJson.examType!='现场考试'){
			zebra_Dialog_warning("问答题请输入0或者正整数!");
			return ;
		}
		if(!(/(^[0-9]\d*$)/.test(dataJson.fillCount))&&dataJson.examType!='现场考试'){
			zebra_Dialog_warning("填空题请输入0或者正整数!");
			return ;
		}
		if(dataJson.examType=='考试试卷'){
			if(dataJson.askCount>0){
				zebra_Dialog_warning("考试试题中不能包含问答题!");
				return ;
			}
		}
		if(!(/^\d+(\.\d+)?$/.test(dataJson.radioScore))&&!(/(^[0-9]\d*$)/.test(dataJson.radioScore))&&dataJson.examType!='现场考试'){
			zebra_Dialog_warning("单选题分值请输入非负数!");
			return ;
		}
		if(!(/^\d+(\.\d+)?$/.test(dataJson.checkScore))&&!(/(^[0-9]\d*$)/.test(dataJson.checkScore))&&dataJson.examType!='现场考试'){
			zebra_Dialog_warning("多选题分值请输入非负数!");
			return ;
		}
		if(!(/^\d+(\.\d+)?$/.test(dataJson.judgeScore))&&!(/(^[0-9]\d*$)/.test(dataJson.judgeScore))&&dataJson.examType!='现场考试'){
			zebra_Dialog_warning("判断题分值请输入非负数!");
			return ;
		}
		if(!(/^\d+(\.\d+)?$/.test(dataJson.fillScore))&&!(/(^[0-9]\d*$)/.test(dataJson.fillScore))&&dataJson.examType!='现场考试'){
			zebra_Dialog_warning("填空题分值请输入非负数!");
			return ;
		}
		if(!(/^\d+(\.\d+)?$/.test(dataJson.askScore))&&!(/(^[0-9]\d*$)/.test(dataJson.askScore))&&dataJson.examType!='现场考试'){
			zebra_Dialog_warning("问答题分值请输入非负数!");
			return ;
		}
		var qids=dataJson.qids;
		if(qids==undefined&&dataJson.examType!='现场考试'){
			zebra_Dialog_warning("请自动或者手动生成试卷!");
			return ;
		}
		if(qids!=undefined&&dataJson.examType!='现场考试'){
			var ss=0;
			$.each(qids,function(i,e){
        		if((e.length>1&&e.indexOf("-")>-1)||(e==="-")){
        			ss++;
        		}
        	});
			var num=parseInt(dataJson.radioCount)+parseInt(dataJson.checkCount)+parseInt(dataJson.judgeCount)+parseInt(dataJson.fillCount)+parseInt(dataJson.askCount);
			if(num!=ss){
				zebra_Dialog_warning("题目总数和生成试题总数不相等!");
				return ;
			}
		}
	
	return true;
}
function hiddenScore(examType){
	if(examType==="考试试卷"){
		$("#askScore").attr("readonly",true).val(0);
		$("#askCount").attr("readonly",true).val(0);
		$("#note").show();
	}else{
		if($("input[name='id']").val()!==undefined){
			$("#askScore").attr("readonly",false);
			$("#askCount").attr("readonly",false);
		}else{
			$("#askScore").attr("readonly",false).val(0);
			$("#askCount").attr("readonly",false).val(0);
		}
		
		$("#note").hide();
	}
	
}

